package com.runfast.waimai.web.controller;

import com.runfast.waimai.utils.UploadImageUtil;
import com.runfast.common.web.entity.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

/**
 * @author: Mr.Jiao
 * @date: 2018年08月15日
 */
@RestController(value = "fileuploadController")
@RequestMapping(value = "/sever/upload")
public class FileuploadController {

    @Value(value = "qiniu.access.key")
    private String ACCESS_KEY;
    @Value(value = "qiniu.secret.key")
    private String SECRET_KEY;
    @Value(value = "qiniu.bucket")
    private String BUCKET_NAME;

    /**
     * 图片上传
     * @param file
     * @return
     */
    @PostMapping(value = "/imagesingle",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public Result<?> uploadImage(MultipartFile file){
        if (Objects.isNull(file) || file.isEmpty()) {
            return Result.fail(null,"图片内容无法识别");
        }
        UploadImageUtil utils = new UploadImageUtil(this.ACCESS_KEY, this.SECRET_KEY, this.BUCKET_NAME);
        if(!utils.supported(file.getOriginalFilename())){
            return Result.fail(null, "不支持的图片类型");
        }
        String suffix = utils.getExtension(file.getOriginalFilename());
        //生成新的文件名
        String filename = UUID.randomUUID().toString().replaceAll("-","").toLowerCase() + suffix;
        String qiniuKey = null;
        try {
            qiniuKey = utils.execute(filename, file.getInputStream());
        } catch (IOException e) {
            return Result.fail(null,"图片上传失败");
        }
        return Result.ok("ok", qiniuKey);
    }

}
